package br.com.seosoft.simplecalcfinan;

import java.util.Date;
import java.util.Locale;

import junit.framework.Test;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.util.Log;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;
import br.com.seosoft.simplecalcfinan.utils.ReceberSMS;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;

public class Config extends SherlockPreferenceActivity {
	private ListPreference listaDeSons;
	private CheckBoxPreference smsDetect, setSenha;
	private Preference versaoInstalada, bugSugestao;
	private String version;
	SharedPreferences preference;
	SharedPreferences.Editor editor;
	boolean autenticacao;

	Resources res;
	String[] sons;

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		// ANIMACAO DAS TELAS
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);

		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		String local = Locale.getDefault().toString();
		Intent it = new Intent();
		preference = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		editor = preference.edit();

		autenticacao = preference.getBoolean("senha", false);
		// Seta a mensagem de retorno
		it.putExtra("atualizar", "sim");

		// Seta o status do resultado e a Intent
		setResult(1, it);

		addPreferencesFromResource(R.xml.config);

		res = getResources();
		sons = res.getStringArray(R.array.arraySons);

		smsDetect = (CheckBoxPreference) findPreference("SMS");
		listaDeSons = (ListPreference) findPreference("listaDeSons");

		Log.i(geral.LogCat, "Locale: " + local);

		if (listaDeSons.getValue().equals("coin01")) {

			listaDeSons.setSummary(sons[0]);

		}

		if (listaDeSons.getValue().equals("cashregister05")) {

			listaDeSons.setSummary(sons[1]);

		}

		if (listaDeSons.getValue().equals("mariocoins")) {

			listaDeSons.setSummary(sons[2]);

		}

		listaDeSons
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

					private MediaPlayer mp;

					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						// TODO Auto-generated method stub

						if (newValue.toString().equals("coin01")) {

							listaDeSons.setSummary(sons[0]);
							
							 mp = MediaPlayer.create(Config.this, R.raw.coin01);
							 
			                    mp.setOnCompletionListener(new OnCompletionListener() {

			                        @Override
			                        public void onCompletion(MediaPlayer mp) {
			                            // TODO Auto-generated method stub
			                            mp.release();
			                        }

			                    });   
			                    mp.start();

						}

						if (newValue.toString().equals("cashregister05")) {

							listaDeSons.setSummary(sons[1]);
							
							mp = MediaPlayer.create(Config.this, R.raw.cashregister05);
							 
		                    mp.setOnCompletionListener(new OnCompletionListener() {

		                        @Override
		                        public void onCompletion(MediaPlayer mp) {
		                            // TODO Auto-generated method stub
		                            mp.release();
		                        }

		                    });   
		                    mp.start();

						}

						if (newValue.toString().equals("mariocoins")) {

							listaDeSons.setSummary(sons[2]);
							
							mp = MediaPlayer.create(Config.this, R.raw.mariocoins);
							 
		                    mp.setOnCompletionListener(new OnCompletionListener() {

		                        @Override
		                        public void onCompletion(MediaPlayer mp) {
		                            // TODO Auto-generated method stub
		                            mp.release();
		                        }

		                    });   
		                    mp.start();

						}

						return true;
					}
				});

		smsDetect.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				if (smsDetect.isChecked()) {
					BancoDados bd = new BancoDados(getApplicationContext(),false);
					bd.setPastaSms();
					EasyTracker.getTracker().sendEvent("SMS Detect",
							"Ativou SMS detect", "smsDetect", null);
					ComponentName component = new ComponentName(
							getApplicationContext(), ReceberSMS.class);

					getPackageManager().setComponentEnabledSetting(component,
							PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
							PackageManager.DONT_KILL_APP);

				} else {
					EasyTracker.getTracker().sendEvent("SMS Detect",
							"Desativou SMS detect", "smsDetect", null);
					ComponentName component = new ComponentName(
							getApplicationContext(), ReceberSMS.class);

					getPackageManager().setComponentEnabledSetting(component,
							PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
							PackageManager.DONT_KILL_APP);

				}
				return true;
			}
		});

		if (!local.equalsIgnoreCase("pt_BR")) {

			// smsDetect.setEnabled(false);

		}

		PackageInfo pInfo;
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			version = pInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e(geral.LogCat, "erro obter nome pacote: " + e.getMessage());
			Tracker myTracker = EasyTracker.getTracker(); // Get a reference to
			// tracker.
			myTracker.sendException(e.getMessage(), false); // false indicates
			// non-fatal
			// exception.
		}

		versaoInstalada = (Preference) findPreference("VERSION");
		versaoInstalada.setSummary(version);
		bugSugestao = (Preference) findPreference("bug");
		setSenha = (CheckBoxPreference) findPreference("senha");

		bugSugestao
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference preference) {
						// TODO Auto-generated method stub
						/*
						 * Intent itSend = new
						 * Intent(android.content.Intent.ACTION_SEND);
						 * itSend.setType("plain/text");
						 * itSend.putExtra(android.content.Intent.EXTRA_EMAIL,
						 * new String[]{ "duanniston@gmail.com"});
						 * itSend.putExtra(android.content.Intent.EXTRA_SUBJECT,
						 * "Simple Calc Finan Pro - Bugs and suggestions");
						 * itSend.putExtra(android.content.Intent.EXTRA_TEXT,
						 * caixaDeTexto.getText().toString());
						 * startActivity(itSend);
						 */
						Intent itSend = new Intent(
								android.content.Intent.ACTION_SEND);
						itSend.setType("plain/text");
						itSend.putExtra(android.content.Intent.EXTRA_EMAIL,
								new String[] { "duanniston@gmail.com" });
						itSend.putExtra(android.content.Intent.EXTRA_SUBJECT,
								"Simple Calc Finan Pro - Bugs and suggestions");
						startActivity(Intent.createChooser(itSend,
								"Enviar email com.."));

						return true;
					}

				});

		setSenha.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				if (setSenha.isChecked()) {
					editor.putBoolean("senha", false);
					editor.commit();
					Intent it = new Intent(getApplicationContext(), Senha.class);
					startActivity(it);

				} else {

					editor.putBoolean("senha", false);
					editor.commit();

				}

				return true;
			}
		});

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this); // Add this method.

	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {

		case android.R.id.home:
			finish();

			break;

		default:
			break;
		}
		return true;
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this); // Add this method.
		// VERIFICA INTERVALO PRA PEDIR SENHA

		int intervaloTempo = 0;
		Date data = new Date(System.currentTimeMillis());

		if (geral.intervaloInteracao != null) {

			intervaloTempo = geral.intervaloInteracao.compareTo(data);
			Log.i(geral.LogCat, "TEMPO INTERVALO: " + intervaloTempo);
			Log.i(geral.LogCat, "TEMPO onStart: " + data.getTime());

			if (intervaloTempo == -1) {

				geral.logado = false;

			}
		}

		// geral.logado = false;
		Log.v(geral.LogCat, "autenticacao : " + autenticacao);
		if (autenticacao == true && geral.logado == false) {

			Intent it = getIntent();

			Intent solicitarSenha = new Intent(getApplicationContext(),
					SolicitarSenha.class);

			solicitarSenha.replaceExtras(it);
			solicitarSenha.setData(it.getData());
			solicitarSenha.putExtra("class", getClass().getName());

			startActivity(solicitarSenha);

			Log.v(geral.LogCat, "autenticacao : " + autenticacao);
			finish();

			Log.v(geral.LogCat, "nome da class passando : "
					+ getClass().getName());

		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		boolean senha = preference.getBoolean("senha", false);

		setSenha.setChecked(senha);

		super.onResume();
	}

	@Override
	public void onUserInteraction() {
		// TODO Auto-generated method stub

		Date data = new Date(System.currentTimeMillis()
				+ preference.getInt("tempo", 30000));

		geral.intervaloInteracao = data;
		Log.i(geral.LogCat, ">>>INTERA����O<<<");
		Log.i(geral.LogCat, "TEMPO: " + geral.intervaloInteracao.getTime());
		Log.i(geral.LogCat,
				"TEMPO SETADO COM SENHA: " + preference.getInt("tempo", 30000));

		super.onUserInteraction();
	}

}
